#include "StdAfx.h"
#include "Toolhelp32Func.h"

LPWSTR CToolHelp32Func::m_sDllName = L"kernel32.dll";

CToolHelp32Func::CToolHelp32Func()
: m_bInit(FALSE),
m_hMod(NULL)
{
    
}

CToolHelp32Func::~CToolHelp32Func()
{
    UnInitialize();
}

BOOL CToolHelp32Func::Initialize()
{
    if (!m_bInit)
    {
        m_hMod = ::LoadLibrary(m_sDllName);
        if (m_hMod)
        {
            m_pFunCreateToolhelp32Snapshot = (PFUN_CreateToolhelp32Snapshot)::GetProcAddress(m_hMod, "CreateToolhelp32Snapshot");
            m_pFunModule32FirstW = (PFUN_Module32FirstW)::GetProcAddress(m_hMod, "Module32FirstW");
            m_pFunModule32NextW = (PFUN_Module32NextW)::GetProcAddress(m_hMod, "Module32NextW");

            if (m_pFunCreateToolhelp32Snapshot && m_pFunModule32FirstW && m_pFunModule32NextW)
            {
                m_bInit = TRUE;
            }
            else
            {
                ::FreeLibrary(m_hMod);
                m_hMod = NULL;
            }
        }
    }
    
    return m_bInit;
}

VOID CToolHelp32Func::UnInitialize()
{
    if (m_bInit && m_hMod)
    {
        ::FreeLibrary(m_hMod);
        m_hMod = NULL;
        m_bInit = FALSE;
    }
}

HANDLE CToolHelp32Func::FunCreateToolhelp32Snapshot(DWORD dwFlags, DWORD th32ProcessID)
{
    if (m_bInit)
    {
        return (*m_pFunCreateToolhelp32Snapshot)(dwFlags, th32ProcessID);
    }
    
    return NULL;
}

BOOL CToolHelp32Func::FunModule32FirstW(HANDLE hSnapshot, LPMODULEENTRY32W lpme)
{
    if (m_bInit)
    {
        return (*m_pFunModule32FirstW)(hSnapshot, lpme);
    }

    return m_bInit;
}

BOOL CToolHelp32Func::FunModule32NextW(HANDLE hSnapshot, LPMODULEENTRY32W lpme)
{
    if (m_bInit)
    {
        return (*m_pFunModule32NextW)(hSnapshot, lpme);
    }

    return m_bInit;
}